package com.kaifamiao.dispatch;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;

@WebServlet( "/file/download" )
public class FileDownloadServlet extends HttpServlet {

    // 记录文件保存路径的字段
    private File store ;

    @Override
    public void init() throws ServletException {
        ServletContext sc = this.getServletContext();
        String location = sc.getInitParameter( "location" );
        store = new File( location );
    }

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {

        // 从 QueryString 中获取文件名称
        String filename = request.getParameter( "filename" );
        // 对文件名进行解码
        filename = URLDecoder.decode( filename , Charset.forName( "UTF-8" ) );

        File fod = new File( store , filename );
        // 若 fod 表示的路径在磁盘上是存在的并且是个文件
        if( fod.exists() && fod.isFile() ) {
            // 设置MIME类型
            response.setHeader( "content-type" , "application/octet-stream" );
            filename = URLEncoder.encode( filename , Charset.forName( "UTF-8" ) );
            // 设置响应头中的 content-disposition 字段
            response.setHeader( "content-disposition" , "attachment;filename=" + filename );
            // 获取可以向"响应对象"输出字节数据的输出流
            OutputStream output = response.getOutputStream();
            InputStream input = new FileInputStream( fod );
            int n ;
            byte[] buffer = new byte[ 1 << 20 ];
            while ( ( n = input.read( buffer ) ) != -1 ) {
                output.write( buffer , 0 , n );
            }
            input.close();
        } else {
            response.setCharacterEncoding( "UTF-8" );
            response.setContentType( "text/html;charset=UTF-8" );
            // 获取可以向"响应对象"输出字符数据的打印流
            PrintWriter out = response.getWriter();
            out.println( "<p style=\"color:red;\">文件下载失败，这可能是服务器上不存在该文件所导致的</p>" );
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new IllegalStateException( "不支持POST方式获取文件" );
    }
}
